package com.cloudfun.campusshare.service.handler;

import com.cloudfun.campusshare.common.constant.DelayMsgType;
import com.cloudfun.campusshare.common.constant.OrderStatus;
import com.cloudfun.campusshare.common.security.AuthenticationHolder;
import com.cloudfun.campusshare.common.security.UserAuthentication;
import com.cloudfun.campusshare.entity.OrderEntity;
import com.cloudfun.campusshare.repo.OrderEntityRepo;
import com.cloudfun.campusshare.sender.DelayMessage;
import com.cloudfun.campusshare.service.DeviceOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.Optional;

/**
 * @author : zhangyongjie
 * @version : 1.0
 * @createTime : 2020/6/18 19:45
 * @description :
 */
@Component
public class PayExpireMsgHandler implements DelayMessageHandler {

    @Resource
    private OrderEntityRepo orderEntityRepo;

    @Autowired
    private DeviceOrderService deviceOrderService;

    @Override
    public DelayMsgType support() {
        return DelayMsgType.EXPIRE_PAY_ORDER_CANCEL;
    }

    @Override
    @Transactional
    public void handleMessage(DelayMessage message) {
        Optional<OrderEntity> order = orderEntityRepo.findById(message.getOrderId());
        OrderEntity oe = order.get();
        //超时未支付关闭订单
        if (OrderStatus.WAIT_PAY.equals(oe.getOrderStatus())) {
            oe.setOrderStatus(OrderStatus.TRADE_CLOSE);
            oe.setUpdateTime(String.valueOf(Instant.now().toEpochMilli()));
            orderEntityRepo.save(oe);
            // 超时未支付检查设备是否被锁定，释放锁
            try{
                prepareUserContext(message);
                deviceOrderService.transferOrReleaseDeviceLock(message.getDeviceId());
            }finally {
                destroyUserContext();
            }
        }

    }
}
